package com.example.picture_sharing_system;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.accounts.NetworkErrorException;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.NinePatch;
import android.os.Bundle;
import android.os.NetworkOnMainThreadException;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;
import org.json.JSONStringer;
import org.w3c.dom.Text;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.BlockingDeque;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import utils.BaseResponse;
import utils.Constants;
import utils.Works;

public class PublishWorkActivity extends AppCompatActivity {

    private EditText edt_message;
    private ImageView img_picture;
    private Button btn_publish;
    private int flag;
    private ImageView img_left;
    private Button btn_cancel;

    byte[] test;
    String result;

    private int userid;


    private okhttp3.Callback callback = new okhttp3.Callback() {

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            if (response.isSuccessful()) {
                final String body = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Gson gson = new Gson();
                        Type jsonType =
                                new TypeToken<BaseResponse<List<Works>>>() {
                                }.getType();
                        BaseResponse<List<Works>> worksBaseResponse =
                                gson.fromJson(body, jsonType);

                        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                        intent.putExtra("userid", userid);


                        startActivity(intent);
                        finish();

//                        ImageView test_img = findViewById(R.id.img_test);
////                        worksBaseResponse.getData().get(0).getPictureBase64()
//                        byte[] test2 = Base64.decode(worksBaseResponse.getData().get(0).getPictureBase64(), Base64.DEFAULT);
//                        Bitmap bitmapTest = BitmapFactory.decodeByteArray(test2, 0, test2.length);
//                        test_img.setImageBitmap(bitmapTest);
                    }
                });
            }
        }

        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e) {
            e.printStackTrace();
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_work);

        initData();


        Intent intent = getIntent();
        String picturePath = intent.getStringExtra("picturePath");

        userid = intent.getIntExtra("userid", 0);
        edt_message.setText(intent.getStringExtra("message"));
        flag = intent.getIntExtra("flag", 0);
        if (picturePath != null) {

            Glide.with(getApplicationContext()).load(picturePath).into(img_picture);

        }


        img_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });


        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });


        img_picture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog();
            }
        });

        btn_publish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String message = edt_message.getText().toString();

                if (message.length() <= 0) {
                    Toast.makeText(getApplicationContext(), "文字不能为空", Toast.LENGTH_SHORT).show();
                } else if (flag == 0) {
                    Toast.makeText(getApplicationContext(), "未上传照片", Toast.LENGTH_SHORT).show();
                } else {

                    publish();

                    Toast.makeText(getApplicationContext(), "成功发布", Toast.LENGTH_LONG).show();

                }


            }
        });

    }

    public void dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示")
                .setMessage("请选择以哪种方式上传照片")
                .setPositiveButton("相册", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String message = edt_message.getText().toString();
                        Intent intent = new Intent(getApplicationContext(), SelectPictureActivity.class);
                        intent.putExtra("message", message);
                        intent.putExtra("userid", userid);

                        startActivity(intent);
                        finish();
                    }
                })
                .setNegativeButton("拍照", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(intent, 0);
                    }
                });
        builder.create().show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap bitmap = (Bitmap) extras.get("data");
            img_picture.setImageBitmap(bitmap);
            flag = 1;
        }
    }

    public void publish() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                img_picture.setDrawingCacheEnabled(true);
                Bitmap bitmap = img_picture.getDrawingCache();

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

                byte[] bytes = stream.toByteArray();

                result = Base64.encodeToString(bytes, Base64.DEFAULT);

                test = Base64.decode(result, Base64.DEFAULT);
//
//                Bitmap bitmapTest = BitmapFactory.decodeByteArray(test, 0, test.length);
//
//                img_test.setImageBitmap(bitmapTest);
//
//
                img_picture.setDrawingCacheEnabled(false);

                RequestBody body = new FormBody.Builder()
                        .add("pictureBase64", result)
                        .add("userid", String.valueOf(userid))
                        .add("message", edt_message.getText().toString())
                        .build();

                Request request = new Request.Builder()
                        .url(Constants.PUBLISH_WORK_URL)
                        .post(body).build();

                try {
                    OkHttpClient client = new OkHttpClient();
                    client.newCall(request).enqueue(callback);
                } catch (NetworkOnMainThreadException ex) {
                    ex.printStackTrace();
                }

            }
        }).start();


    }

    public void initData() {
        edt_message = findViewById(R.id.edt_message);
        img_picture = findViewById(R.id.img_picture);
        btn_publish = findViewById(R.id.btn_publish);
        img_left = findViewById(R.id.img_left);
        btn_cancel = findViewById(R.id.btn_cancel);
    }


    @Override
    public void onBackPressed() {
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        intent.putExtra("userid", userid);


        startActivity(intent);

        finish();

    }
}